import Vue from 'vue'
import App from './App.vue'
import Start from './Start.vue';
import store from './store';
import axios from 'axios';
import router from './router';
import { Button, Select, Option,  Icon, Form,Input, FormItem,Dropdown, DropdownMenu, DropdownItem, Loading, Pagination, Message } from 'element-ui';
import '@assets/styles/reset.css';
import '@assets/styles/main.sass';
import 'element-ui/lib/theme-chalk/index.css';
import * as TYPES from './store/types';
import AMap from 'vue-amap';
Vue.use(AMap);
// 初始化vue-amap
AMap.initAMapApiLoader({
  key: '8ced2900d081fd2df2f3554775d483c9',
  plugin: ['AMap.Geolocation']

});
Vue.use(Button);
Vue.use(Select);
Vue.use(Option);
Vue.use(Dropdown);
Vue.use(DropdownMenu);
Vue.use(DropdownItem);
Vue.use(Icon);

Vue.use(Input);
Vue.use(Form);
Vue.use(FormItem);

Vue.use(Pagination);
Vue.use(Loading.directive);
Vue.prototype.$loading = Loading.service;
Vue.prototype.$message = Message;
Vue.prototype.axios = axios;
Vue.config.productionTip = false;

//统一增加参数
axios.interceptors.request.use((config) => {
  config.headers.Authorization = `Bearer ${localStorage.getItem('ACCESS_TOKEN')}`;
  let { sources } = router.history.current.query;
  let parameter = {};
  if (sources) {
    parameter = {
      sources: decodeURIComponent(sources)
    };
  }
  if (config.method === 'post') {
    config.data = JSON.stringify({
      ...parameter,
      ...config.data
    })
  } else
    if (config.method === 'get') {
      config.params = {
        ...parameter,
        ...config.params
      };
    }
  return config;
})

axios.interceptors.response.use(
  resp => {
    let { data: { errno }, status } = resp;
    if (errno === 401) {
      //登录
    }
    if (status !== 200) {
      this.$message.error('请求错误');
    }
    return resp;
  }
);
let mainObj = {
  getProfile(callback = () => { }) {
    axios.get('/ctepapi/admin-api/system/user/profile/get').then(resp => {
      let { code, data } = resp.data;
      if (code * 1 === 0) {
        store.commit(TYPES.GLOBAL_TYPES.SAVE_USER_ACTION, data);
      } else {
        window.localStorage.removeItem('ACCESS_TOKEN');
      }
    });
  },
  initContainer() {
    let container = document.getElementById('app');
    if (!container) {
      container = document.createElement('div');
      container.id = 'app';
      document.body.appendChild(container);
    }
  },

  initApp() {
    mainObj.initContainer();
    new Vue({
      router,
      store,
      render: h => h(App),
    }).$mount('#app');

  },
  init() {
    mainObj.initContainer();
    new Vue({
      render: h => h(Start),
    }).$mount('#app');
    this.getProfile();
    setTimeout(() => {
      mainObj.initApp();
    }, 10)
  }
};
mainObj.init();